import { createApp } from 'vue'

//根组件
import App from './App.vue'

//引入UI框架
import vant from 'vant'
import 'vant/lib/index.css'
import { Lazyload } from 'vant';

// 引入封装路由模块
import router from './routers/index'

//引入封装的请求插件
import request from './services/request'

//引入我们自己构建的工具栏
import tools from './services/tools'

//引入cookie工具
import VueCookies from 'vue3-cookies'

//挂载的实际意义是让应用具备某项功能
const app = createApp(App)
    .use(tools) // -> install
    .use(VueCookies)
    .use(vant)
    .use(Lazyload)
    .use(request)
    .use(router)
    .mount('#app')

//路由守卫 进入到下一个路由前的钩子
router.beforeEach(async (to, from, next) => {
    //判断meta是否有这个属性
    var login = to.meta.login ? to.meta.login : false

    if(login)
    {
        // console.log('需要登录')
        var business = app.$cookies.get('business') ? app.$cookies.get('business') : {}

        //对象是空
        if(typeof business != 'object' && Object.getOwnPropertyNames(business).length <= 0)
        {
            app.$cookies.remove('business');
            next('/business/login');
            return false
        }

        //对象下面是否有id 和 Mobile
        var id = business.id ? business.id : 0;
        var mobile = business.mobile ? business.mobile : '';

        if(!id || !mobile)
        {
            app.$cookies.remove('business');
            next('/business/login');
            return false
        }

        //发起请求，判断用户是否存在
        var result = await app.$POST({
            url: '/business/check',
            params: {id, mobile}
        })

        if(result.code == 0)
        {
            //删除cookie
            app.$cookies.remove('business');
            next(result.url)
            return false
        }

        //如果有找到我们就覆盖cookie
        app.$cookies.set('business', result.data)
        next()
    }else
    {
        //不需要登录
        next()
        return false
    }
})